<template>
  <div class="preview-image-container">
    <n-popover
      trigger="hover"
      :show-arrow="false"
      :disabled="hoverPreviewDisabled"
      placement="right-end"
      v-bind="popoverProps"
      :style="{ transform: `scale(${imgScale})`, padding: 0 }"
      content-style="display: flex"
      display-directive="show"
    >
      <template #trigger>
        <n-image
          v-loading="{
            show: loading1,
            text: '',
            size: 'small'
          }"
          width="200"
          preview-disabled
          v-bind="$attrs"
          :src="src"
          @load="loading1 = false"
        />
      </template>
      <n-image
        v-loading="{
          show: loading2,
          text: '',
          size: 'small'
        }"
        width="200"
        preview-disabled
        v-bind="$attrs"
        :src="src"
        @mousewheel="onMousewheel"
        @load="loading2 = false"
      />
    </n-popover>
  </div>
</template>

<script lang="ts" setup name="ProImage">
  interface PropType {
    src: string
    /**  禁止鼠标滑轮滚动时进行放大/缩小  **/
    scaleDisabled?: boolean
    /**  禁止悬浮时预览窗口  **/
    hoverPreviewDisabled?: boolean
    /**  popover参数  **/
    popoverProps?: object
    /**  	默认放大倍率  **/
    scale?: number
    /**  最低放大倍率  **/
    minScale?: number
    /**  最高放大倍率  **/
    maxScale?: number
    /**  滚动一次的放大/缩小的幅度  **/
    scaleOnce?: number
  }

  const props = withDefaults(defineProps<PropType>(), {
    scaleDisabled: false,
    hoverPreviewDisabled: true,
    popoverProps: () => ({}),
    scale: 1.5,
    minScale: 1,
    maxScale: 2.5,
    scaleOnce: 0.2
  })

  const loading1 = ref(true)
  const loading2 = ref(true)

  const imgScale = ref(props.scale)

  const onMousewheel = (e) => {
    if (props.scaleDisabled) return
    const { minScale, maxScale, scaleOnce } = props
    if (e.deltaY >= 125) {
      // 缩小
      if (imgScale.value <= minScale) return
      if (imgScale.value - minScale < scaleOnce) {
        imgScale.value = minScale
      } else {
        imgScale.value -= scaleOnce
      }
    } else if (e.deltaY <= -125) {
      // 放大
      if (imgScale.value >= maxScale) return
      if (maxScale - imgScale.value < scaleOnce) {
        imgScale.value = maxScale
      } else {
        imgScale.value += scaleOnce
      }
    }
  }
</script>

<style lang="less" scoped></style>
